package org.example.controller;

import org.example.device.control.DeviceControlCommand;
import org.example.device.control.DeviceControlResult;
import org.example.device.service.RealDeviceControlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 真实设备控制器
 * 提供真实设备控制的REST API
 */
@RestController
@RequestMapping("/real-devices")
@CrossOrigin(origins = "*")
public class RealDeviceController {
    
    @Autowired
    private RealDeviceControlService realDeviceControlService;
    
    /**
     * 执行设备控制命令
     */
    @PostMapping("/{deviceId}/control")
    public ResponseEntity<?> controlDevice(@PathVariable Long deviceId, @RequestBody DeviceControlCommand command) {
        try {
            command.setDeviceId(deviceId);
            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("设备控制失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取设备状态
     */
    @GetMapping("/{deviceId}/status")
    public ResponseEntity<?> getDeviceStatus(@PathVariable Long deviceId) {
        try {
            Map<String, Object> status = realDeviceControlService.getDeviceStatus(deviceId);
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "获取设备状态失败: " + e.getMessage()));
        }
    }
    
    /**
     * 检查设备是否在线
     */
    @GetMapping("/{deviceId}/online")
    public ResponseEntity<?> isDeviceOnline(@PathVariable Long deviceId) {
        try {
            boolean isOnline = realDeviceControlService.isDeviceOnline(deviceId);
            return ResponseEntity.ok(Map.of("online", isOnline));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "检查设备在线状态失败: " + e.getMessage()));
        }
    }
    
    /**
     * 测试设备连接
     */
    @PostMapping("/{deviceId}/test-connection")
    public ResponseEntity<?> testDeviceConnection(@PathVariable Long deviceId) {
        try {
            DeviceControlResult result = realDeviceControlService.testDeviceConnection(deviceId);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("设备连接测试失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取设备支持的指令
     */
    @GetMapping("/{deviceId}/commands")
    public ResponseEntity<?> getDeviceCommands(@PathVariable Long deviceId) {
        try {
            List<String> commands = realDeviceControlService.getDeviceSupportedCommands(deviceId);
            return ResponseEntity.ok(Map.of("commands", commands));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "获取设备指令失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取设备属性
     */
    @GetMapping("/{deviceId}/properties")
    public ResponseEntity<?> getDeviceProperties(@PathVariable Long deviceId) {
        try {
            Map<String, Object> properties = realDeviceControlService.getDeviceProperties(deviceId);
            return ResponseEntity.ok(properties);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "获取设备属性失败: " + e.getMessage()));
        }
    }
    
    /**
     * 设置设备属性
     */
    @PutMapping("/{deviceId}/properties")
    public ResponseEntity<?> setDeviceProperties(@PathVariable Long deviceId, @RequestBody Map<String, Object> properties) {
        try {
            DeviceControlResult result = realDeviceControlService.setDeviceProperties(deviceId, properties);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("设置设备属性失败: " + e.getMessage()));
        }
    }
    
    /**
     * 智能灯光控制 - 开关
     */
    @PostMapping("/{deviceId}/light/switch")
    public ResponseEntity<?> controlLightSwitch(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Boolean on = (Boolean) request.get("on");
            Long userId = Long.valueOf(request.get("userId").toString());
            
            DeviceControlCommand command = new DeviceControlCommand(deviceId, "switch", on);
            command.setUserId(userId);
            command.setAction("灯光开关控制");
            
            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("灯光开关控制失败: " + e.getMessage()));
        }
    }
    
    /**
     * 智能灯光控制 - 亮度
     */
    @PostMapping("/{deviceId}/light/brightness")
    public ResponseEntity<?> controlLightBrightness(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Integer brightness = (Integer) request.get("brightness");
            Long userId = Long.valueOf(request.get("userId").toString());
            
            DeviceControlCommand command = new DeviceControlCommand(deviceId, "brightness", brightness);
            command.setUserId(userId);
            command.setAction("灯光亮度控制");
            
            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("灯光亮度控制失败: " + e.getMessage()));
        }
    }
    
    /**
     * 智能温控器控制 - 温度
     */
    @PostMapping("/{deviceId}/thermostat/temperature")
    public ResponseEntity<?> controlThermostatTemperature(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Double temperature = Double.valueOf(request.get("temperature").toString());
            Long userId = Long.valueOf(request.get("userId").toString());
            
            DeviceControlCommand command = new DeviceControlCommand(deviceId, "temperature", temperature);
            command.setUserId(userId);
            command.setAction("温度控制");
            
            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("温度控制失败: " + e.getMessage()));
        }
    }
    
    /**
     * 智能摄像头控制 - 开关
     */
    @PostMapping("/{deviceId}/camera/switch")
    public ResponseEntity<?> controlCameraSwitch(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Boolean on = (Boolean) request.get("on");
            Long userId = Long.valueOf(request.get("userId").toString());
            
            DeviceControlCommand command = new DeviceControlCommand(deviceId, "switch", on);
            command.setUserId(userId);
            command.setAction("摄像头开关控制");
            
            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("摄像头开关控制失败: " + e.getMessage()));
        }
    }
    
    /**
     * 智能摄像头控制 - 录制
     */
    @PostMapping("/{deviceId}/camera/record")
    public ResponseEntity<?> controlCameraRecord(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Boolean record = (Boolean) request.get("record");
            Long userId = Long.valueOf(request.get("userId").toString());
            
            DeviceControlCommand command = new DeviceControlCommand(deviceId, "record", record);
            command.setUserId(userId);
            command.setAction("录制控制");
            
            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("录制控制失败: " + e.getMessage()));
        }
    }
    
    /**
     * 智能摄像头控制 - 快照
     */
    @PostMapping("/{deviceId}/camera/snapshot")
    public ResponseEntity<?> takeCameraSnapshot(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());

            DeviceControlCommand command = new DeviceControlCommand(deviceId, "snapshot", null);
            command.setUserId(userId);
            command.setAction("拍摄快照");

            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);

            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("拍摄快照失败: " + e.getMessage()));
        }
    }

    /**
     * 智能摄像头控制 - 夜视模式
     */
    @PostMapping("/{deviceId}/camera/night-vision")
    public ResponseEntity<?> controlCameraNightVision(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Boolean enabled = (Boolean) request.get("enabled");
            Long userId = Long.valueOf(request.get("userId").toString());

            DeviceControlCommand command = new DeviceControlCommand(deviceId, "night_vision", enabled);
            command.setUserId(userId);
            command.setAction("夜视模式控制");

            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);

            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("夜视模式控制失败: " + e.getMessage()));
        }
    }

    /**
     * 智能摄像头控制 - 分辨率设置
     */
    @PostMapping("/{deviceId}/camera/resolution")
    public ResponseEntity<?> setCameraResolution(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            String resolution = (String) request.get("resolution");
            Long userId = Long.valueOf(request.get("userId").toString());

            DeviceControlCommand command = new DeviceControlCommand(deviceId, "resolution", resolution);
            command.setUserId(userId);
            command.setAction("分辨率设置");

            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);

            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("分辨率设置失败: " + e.getMessage()));
        }
    }

    /**
     * 智能摄像头控制 - 水平角度调节
     */
    @PostMapping("/{deviceId}/camera/pan")
    public ResponseEntity<?> controlCameraPan(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Integer angle = (Integer) request.get("angle");
            Long userId = Long.valueOf(request.get("userId").toString());

            DeviceControlCommand command = new DeviceControlCommand(deviceId, "pan", angle);
            command.setUserId(userId);
            command.setAction("水平角度调节");

            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);

            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("水平角度调节失败: " + e.getMessage()));
        }
    }

    /**
     * 智能摄像头控制 - 垂直角度调节
     */
    @PostMapping("/{deviceId}/camera/tilt")
    public ResponseEntity<?> controlCameraTilt(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Integer angle = (Integer) request.get("angle");
            Long userId = Long.valueOf(request.get("userId").toString());

            DeviceControlCommand command = new DeviceControlCommand(deviceId, "tilt", angle);
            command.setUserId(userId);
            command.setAction("垂直角度调节");

            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);

            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("垂直角度调节失败: " + e.getMessage()));
        }
    }

    /**
     * 智能摄像头控制 - 开始巡航
     */
    @PostMapping("/{deviceId}/camera/patrol/start")
    public ResponseEntity<?> startCameraPatrol(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());

            DeviceControlCommand command = new DeviceControlCommand(deviceId, "patrol_start", null);
            command.setUserId(userId);
            command.setAction("开始巡航");

            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);

            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("开始巡航失败: " + e.getMessage()));
        }
    }

    /**
     * 智能摄像头控制 - 停止巡航
     */
    @PostMapping("/{deviceId}/camera/patrol/stop")
    public ResponseEntity<?> stopCameraPatrol(@PathVariable Long deviceId, @RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());

            DeviceControlCommand command = new DeviceControlCommand(deviceId, "patrol_stop", null);
            command.setUserId(userId);
            command.setAction("停止巡航");

            DeviceControlResult result = realDeviceControlService.executeDeviceCommand(deviceId, command);

            if (result.isSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(DeviceControlResult.failure("停止巡航失败: " + e.getMessage()));
        }
    }

    /**
     * 获取摄像头状态
     */
    @GetMapping("/{deviceId}/camera/status")
    public ResponseEntity<?> getCameraStatus(@PathVariable Long deviceId) {
        try {
            Map<String, Object> status = realDeviceControlService.getDeviceStatus(deviceId);
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "获取摄像头状态失败: " + e.getMessage()));
        }
    }
}
